﻿using LibreHardwareMonitor.Hardware;

namespace DesktopToy.Core;

/// <summary>
/// 用于获取CPU温度、硬盘温度等信息。注意：需要有管理员权限
/// </summary>
public class DeviceService
{
    private Computer? Computer;
    private DeviceTemperatureSensor? CpuSensor, GpuSensor, StorageSensor;

    public void Start()
    {
        if (Computer != null) return;
        Computer = new Computer
        {
            IsCpuEnabled = true,
            IsGpuEnabled = true,
            IsMotherboardEnabled = true,
            IsStorageEnabled = true
        };

        Computer.Open();

        foreach (var hardware in Computer.Hardware)
        {
            // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
            switch (hardware.HardwareType)
            {
                case HardwareType.Cpu:
                    CpuSensor = new DeviceTemperatureSensor(hardware);
                    break;
                
                case HardwareType.GpuIntel:
                case HardwareType.GpuNvidia:
                case HardwareType.GpuAmd:
                    GpuSensor = new DeviceTemperatureSensor(hardware);
                    break;

                case HardwareType.Storage:
                    StorageSensor = new DeviceTemperatureSensor(hardware);
                    break;
            }
        }
    }

    public void Stop()
    {
        Computer?.Close();
        Computer = null;
        
        CpuSensor = null;
        GpuSensor = null;
        StorageSensor = null;
    }

    public float GetCpuTemperature()
    {
        if (CpuSensor == null) return 0;
        return CpuSensor.GetTemperature("CPU Package");
    }
    
    public float GetGpuTemperature()
    {
        if (GpuSensor == null) return 0;
        return GpuSensor.GetTemperature("GPU Core");
    }
    
    public float GetStorageTemperature()
    {
        if (StorageSensor == null) return 0;
        return StorageSensor.GetTemperature();
    }
}